<template>
  <div class="mapMarksInfo-container" ref="map">
    <SliteMapViewer @ready="loadMap" :config="config" v-loading="loading"></SliteMapViewer>
    <template v-if="showIntersectTips && intersectList.length > 0">
      <template v-for="(item, index) in  intersectList ">
        <div class="tips-container" :ref="`tipsRef${index}`" :key="`${item.num}ke`">
          <div class="tips-item">
            <div class="tips-left"> 误差距离<br>{{ '【' + item.num +'m' + '】' || '暂无' }}</div>
          </div>
        </div>
      </template>
    </template>
    <template v-if="showPointInfoTips && pointInfo.length > 0">
      <template v-for="(item, index) in  pointInfo ">
        <div class="info-container" :ref="`tipsPointRef${index}`" :key="`${item.ip}ke`">
          <div class="info-item">
            <div class="info-left"> 
              <i style="cursor: pointer; color: rgb(140 143 145)!important; position: absolute; right: 5px; margin-top: 4px; font-size: 16px" class="el-icon-circle-close" @click="closeInfo"></i>
              <p class="titleinfo" v-if="item.type!=null">{{ item.type }}</p>
              <p class="titleinfo" v-if="item.type==null">IP信息</p>
              <p class="info">IP：{{item.ip  || '暂无' }}</p>
              <p class="info">经度：{{item.viewLng  || '暂无' }}</p>
              <p class="info">纬度：{{item.viewLat  || '暂无' }}</p>
            </div>
          </div>
        </div>
      </template>
    </template>
    <el-dialog title="汇聚信息" :visible.sync="dialogjuheVisible" width="50%" append-to-body>
      <div class="total">
        当前汇聚轨迹点位共 <strong style="color:#46a6ff ;">{{ traDetail.length }} </strong>个
      </div>
      <el-table :data="traDetail" style="width: 100%" :row-class-name="tableRowClassName"
        :header-cell-style="{ 'background': '#46a6ff', 'color': '#fff' }">
        <el-table-column type="index" width="100" label="点位序号" align="center"> </el-table-column>
        <el-table-column prop="src_vid" label="主叫" width="180" align="center">
        </el-table-column>
        <el-table-column prop="dst_vid" label="被叫" width="180" align="center">
        </el-table-column>
        <el-table-column prop="lng" label="经度" align="center">
        </el-table-column>
        <el-table-column prop="lat" label="纬度" align="center">
        </el-table-column>
        <el-table-column prop="call_datetime" label="呼叫时间" align="center">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.call_datetime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogjuheVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogjuheVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import SliteMapViewer from './SliteMapViewer.vue'
import markCar from "@/assets/images/map/marker-icon/marker-person-pos.png";
import locationIcon from "@/assets/images/map/marker-icon/location-icon.png";
import * as ol from '@/plugins/map/utils/openLayer'
import 'ol/ol.css';
import { LineString } from 'ol/geom';

export default {
  components: { SliteMapViewer },
  props: {
    showArea: {
      type: Boolean,
      default: () => false
    },
    showIntersect: {
      // 展示误差距离
      type: Boolean,
      default: () => false
    },
    showIntersectTips: {
      // 展示误差距离提示tip
      type: Boolean,
      default: () => false
    },
  },
  data() {
    return {
      nodeCounts:'',
      routeLength:'',
      maxZoom:'',
      selectType:'',
      routeType:'',
      route:'',
      showPointInfo:false,
      showPointInfoTips:false,
      isSetting:'',//ip定位页面，是否需要地图放大效果
      traDetail: [],
      dialogjuheVisible: false,
      dialogVisible: false,
      currentMarksList: [],
      intersectList: [],
      pointInfo:[],
      config: {
        locationConfig: {
          show: false
        }
      },
      mapClass: undefined,
      regionConfig: [],

      tipsContainerRef: null,
      loading: true,
      showTip: false
    };
  },
  watch: {},
  computed: {},
  methods: {
    handlemouseover() {
      this.showTip = !this.showTip
    },

    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'gray-row';
      }
      return '';
    },
    /**
     *
     * @param {*} res 为json格式，包含经纬度(lng,lat)，半径(radius)，和要渲染到地图上的点位列表（points）,units:单位
     */
    setData(res = {}) {
      // console.log('ressssssssssssssss',res)
      this.route = res?.route 
      this.routeLength = res?.routeLength
      this.selectType = res?.selectType 
      this.routeType = res?.routeType
      this.nodeCounts = res?.nodeCounts
      this.showPointInfo = res?.showPointInfo
      this.showPointInfoTips = res?.showPointInfoTips
      this.isSetting = res?.isSetting
      if (res?.intersectionPoints) {
        this.intersectList = res?.intersectionPoints.map(item => {
          return {
            num: item.count,
            points: [item.longitude, item.latitude],
            lng: item.longitude,
            lat: item.latitude,
          }
        })
      }
      this.addPointMarks(res?.markPoints);
      this.addTrajectory(res?.points, res?.route, res?.status, res?.trajectoryPoints);
      if (this.showArea) {
        if (res?.lat && res?.lng && res?.radius) {
          this.regionConfig = [
            {
              lng: res?.lng,
              lat: res?.lat,
              radius: res?.radius,
              units: res.units,
              style: {
                //可以单独设置，不设置，默认找lineConfig->drawEndStyle
                fillColor: "rgba(0, 255, 255, 0.2)",
                strokeColor: "#ffcc33",
                strokeLineDash: [0, 0],
                strokeWidth: 2
              }
            }
          ];
        }
        if (this.intersectList.length > 0) {
          this.intersectList.forEach(item => {
            let config = {
              lng: item.lng,
              lat: item.lat,
              style: {
                //可以单独设置，不设置，默认找lineConfig->drawEndStyle
                fillColor: "rgba(255, 150 ,1, 0.3)",
                strokeColor: "rgba(255, 150 ,1)",
                strokeLineDash: [0, 0],
                strokeWidth: 7
              }
            }
            this.regionConfig.push(config)
          })
        }
        this.addArea();
      } else {
        this.mapClass.onRemoveLayer("id", "DrawShapLayer");
      }
    },
    loadMap(map) {
      this.loading = false;
      this.mapClass = map;
    },
    /**
     * 绘制圆
     */
    addArea() {
      if (this.mapClass.getLayer("id", "DrawShapLayer").length > 0) {
        this.mapClass.onRemoveLayer("id", "DrawShapLayer");
      }
      this.mapClass.addLayer({
        type: "DrawShapLayer",
        shapConfig: {
          type: "CustomCircle",
          dataType: "corrdinates", // 数据类型 有wkt,geogson,corrdinates 等三种类型
          data: this.regionConfig,
          isMultipleBool: true, // 不允许多个存在 false-> 不允许，true -> 允许
          onlyShow: true
        },
        lineConfig: {
          // 线条样式设置
          drawEndStyle: {
            //  统一设置图像 绘制完成样式设置
            fillColor: "rgba(121,187,255,.1)",
            strokeColor: "rgba(121,187,255,.3)",
            strokeLineDash: [0, 0],
            strokeWidth: 2
          }
        }
      })
    },
    /**
     * 绘制轨迹 route为页面，status为路由路径页面的成功或失败的状态，失败没有终点
     */
    addTrajectory(points = [], route, status, trajectoryPoints) {
      if (this.mapClass.getLayer("id", "TrajectoryLayers").length > 0) {
        this.mapClass.onRemoveLayer("id", "TrajectoryLayers");
      }
      // 定义点图标的样式
      const pointStyle = {
        type: "icon", // 图标类型
        iconUrl: "path/to/your/icon.png", // 图标的路径
        iconSize: [32, 32], // 图标大小
        iconAnchor: [16, 16] // 图标锚点
      };
      // 将点转换为包含图标样式的要素数组
      const features = points.map(point => ({
        type: "Feature",
        geometry: {
          type: "Point",
          coordinates: point
        },
        properties: {
          icon: pointStyle
        },
      }));
      this.mapClass.addLayer({
        type: "TrajectoryLayers",
        coordinates: points,
        coordinatesType: "point",
        route:route,
        status:status,
        intersectConfig: this.showIntersect
          ? {
            open: true,
            dataSource: "server", //
            intersectPoints: this.intersectList,
            callback: this.onGetIntersectData(this.intersectList)
          }: {},
        actions: [
          {
            type: "click",
            eventType: "point",
            hitTolerance: 10, // 命中容差
            handle: this.handlePointClick
          },
         
        ]
      });
      if(trajectoryPoints){  //大地图到小地图的放大过程-ip定位页面可选，其他页面默认有放大
        if(this.route == 'location' && this.isSetting == 'true'){
          this.maxZoom = 16
          var lineStringGeometry = new LineString(trajectoryPoints);
          var routeFeature = new ol.Feature({
            geometry: lineStringGeometry,
          })
          var extent = routeFeature.getGeometry().getExtent();
          this.mapClass.map.getView().fit(extent, {
            size: this.mapClass.map.getSize(), // 当前地图容器的尺寸
            padding: [50, 50, 50, 50], // 可选的内边距，用于增加可视空间边缘距离
            maxZoom: this.maxZoom, // 可选的最大缩放级别限制
            duration: 900 // 可选的动画持续时间（单位：毫秒），如果希望平滑过渡
          })
        }else if(this.route == 'topology' && this.selectType == 1 && this.routeType != 1 || this.route == 'topology' && this.selectType == 2 && this.nodeCounts<1000 || this.route == 'topology' && this.selectType == 3 && this.nodeCounts<1000){
          this.maxZoom = 7
          var lineStringGeometry = new LineString(trajectoryPoints);
          var routeFeature = new ol.Feature({
            geometry: lineStringGeometry,
          })
          var extent = routeFeature.getGeometry().getExtent();
          this.mapClass.map.getView().fit(extent, {
            size: this.mapClass.map.getSize(), // 当前地图容器的尺寸
            padding: [50, 50, 50, 50], // 可选的内边距，用于增加可视空间边缘距离
            maxZoom: this.maxZoom, // 可选的最大缩放级别限制
            duration: 900 // 可选的动画持续时间（单位：毫秒），如果希望平滑过渡
          })
        }else if(this.route == 'topology' && this.selectType == 1 && this.routeType == 1 || this.route == 'topology' && this.selectType == 2 && this.nodeCounts==1000 || this.route == 'topology' && this.selectType == 3 && this.nodeCounts==1000){
          this.maxZoom = 12.5
          var lineStringGeometry = new LineString(trajectoryPoints);
          var routeFeature = new ol.Feature({
            geometry: lineStringGeometry,
          })
          var extent = routeFeature.getGeometry().getExtent();
          this.mapClass.map.getView().fit(extent, {
            size: this.mapClass.map.getSize(), // 当前地图容器的尺寸
            padding: [50, 50, 50, 50], // 可选的内边距，用于增加可视空间边缘距离
            maxZoom: this.maxZoom, // 可选的最大缩放级别限制
            duration: 900 // 可选的动画持续时间（单位：毫秒），如果希望平滑过渡
          })
        }else if(this.route == 'tracert' && this.routeLength == 1){
          this.maxZoom = 7
          var lineStringGeometry = new LineString(trajectoryPoints);
          var routeFeature = new ol.Feature({
            geometry: lineStringGeometry,
          })
          var extent = routeFeature.getGeometry().getExtent();
          this.mapClass.map.getView().fit(extent, {
            size: this.mapClass.map.getSize(), // 当前地图容器的尺寸
            padding: [50, 50, 50, 50], // 可选的内边距，用于增加可视空间边缘距离
            maxZoom: this.maxZoom, // 可选的最大缩放级别限制
            duration: 900 // 可选的动画持续时间（单位：毫秒），如果希望平滑过渡
          })
        }else if(this.route == 'tracert' && this.routeLength == 3){
          this.maxZoom = 14
          var lineStringGeometry = new LineString(trajectoryPoints);
          var routeFeature = new ol.Feature({
            geometry: lineStringGeometry,
          })
          var extent = routeFeature.getGeometry().getExtent()
          this.mapClass.map.getView().fit(extent, {
            size: this.mapClass.map.getSize(), // 当前地图容器的尺寸
            padding: [50, 50, 50, 50], // 可选的内边距，用于增加可视空间边缘距离
            maxZoom: this.maxZoom, // 可选的最大缩放级别限制
            duration: 900 // 可选的动画持续时间（单位：毫秒），如果希望平滑过渡
          })
        }
      }
    },
    addPointMarks(points = []) {
      if (this.mapClass.getLayer("id", "MarkerLayer").length > 0) {
        this.mapClass.onRemoveLayer("id", "MarkerLayer");
      }
      /**
       * 未选中样式
       */
      let markStyle = [
        {
          type: "singleMark",
          legend: 1,
          pointType: "image",
          style: {
            url: markCar
          }
        },
        {
          type: "singleMark",
          legend: 2,
          pointType: "image",
          style: {
            url: locationIcon
          }
        }
      ];
      this.mapClass.addLayer({
        type: "MarkerLayer",
        layerStyle: markStyle,
        points,
        actions: [
          {
            type: "click",
            hitTolerance: 10, // 命中容差
            handle: this.handlePointClick
          }
        ]
      });
    },
    /**
     * 得到误差距离
     * @param {*} list
     */
    onGetIntersectData(list) {
      this.intersectList = list
      let overlayerConfigs = [];
      if (this.intersectList.length > 0) {
        if (this.showIntersectTips) {
          // 显示相交点的提示
          this.$nextTick(() => {
            for (let i in this.intersectList) {
              let overlayer = {
                id: `overlayerId${i}`,
                element: this.$refs[`tipsRef${i}`][0],
                position: [this.intersectList[i].lng, this.intersectList[i].lat]
              };
              overlayerConfigs.push(overlayer);
              // console.log('overlayerConfigs', overlayerConfigs)
            }
            this.mapClass.addOverLayers(overlayerConfigs);
          });
        }
      }
    },
    //点击轨迹
    handleLineClick(list) {
      this.$emit("LineClick", list);
    },
    //点击节点
    handlePointClick(list) {
      this.$emit("pointClick", list);
      if (list?.length == 1) {
        this.showPointInfo = true
        this.showPointInfoTips  = true
        this.pointInfo = list
        let overlayerConfigs = [];
        if (this.pointInfo.length > 0) {
          if (this.showPointInfoTips) {
            // 显示信息窗口
            this.$nextTick(() => {
              for (let i in this.pointInfo) {
                let overlayer = {
                  id: `overlayerId${i}`,
                  element: this.$refs[`tipsPointRef${i}`][0],
                  position: [this.pointInfo[i].lng, this.pointInfo[i].lat]
                };
                overlayerConfigs.push(overlayer);
              }
              this.mapClass.addOverLayers(overlayerConfigs);
            });
          }
        }
      }else{
        this.showPointInfo = false
        this.showPointInfoTips = false
      }
    },
    closeInfo(){
      this.showPointInfoTips = false
    }
  },
  created() { },
  mounted() { }
};
</script>
<style lang="scss" scoped>
.mapMarksInfo-container {
  width: 100%;
  height: 100%;
  .tips-container1 {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: rgba(255, 0, 0, 0.267);
    border: 1px solid red;
  }
  .tips-container {
    cursor: pointer;
    .tips-item {
      display:flex;
      -webkit-flex-wrap:nowrap;
      flex-wrap:nowrap;
      align-items: center;
      justify-content: start;
      .tips-left {
        color:#ece7e7;
        opacity: 0.9;
        background: #ce5b5b;
        // background: url('../../assets/images/map/marker-icon/distance2.png') no-repeat;
        width: 130px;
        height: 50px;
        // display: flex;
        border: 2px solid #ce5b5b;
        border-radius: 6px;
        -webkit-flex-wrap:nowrap;
        flex-wrap:nowrap;
        justify-content: center;
        align-items: center;
        background-size: contain;
        font-size: 17px;
        margin-top:-16px;
        margin-left:-110px;
        text-align: center;
      }
    }
  }
  .info-container {
    cursor: pointer;
    .info-item {
      display:flex;
      -webkit-flex-wrap:nowrap;
      flex-wrap:nowrap;
      align-items: center;
      justify-content: start;
      .info-left {
        color: #141414;
        opacity: 0.9;
        background: #fffafa;
        min-width: 16.714286rem;
        height: 10.357143rem;
        border: 2px solid #d6d3d3;
        border-radius: 10px;
        -webkit-flex-wrap: nowrap;
        flex-wrap: nowrap;
        justify-content: center;
        align-items: center;
        background-size: contain;
        font-size: 1.214286rem;
        margin-top: -13.785714rem;
        text-align: center;
        .info{
          line-height:14px
        }
        .titleinfo{
          margin-top:14px
        }
      }
    }
  }
}
</style>
